﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

using System.Text;

/// <summary>
/// BasePage 的摘要说明



/// </summary>
public class BasePage
{
   
    #region 返回网站标题
    public static string WebTitle
    {
        get
        {
            return ConfigurationManager.AppSettings["Title"].ToString();
        }        
    }
    #endregion
    #region 返回是否启用积分
    public static string IsJF
    {
        get
        {
            return "1";
        }
    }
    #endregion
    public BasePage()
    {

    }
    #region 浏览过的商品操作
    public static string UserView_Add(string ProductID)
    {
        if (HttpContext.Current.Request.Cookies["View"] != null)
        {
            string ProductList = HttpContext.Current.Request.Cookies["View"]["ProductID"].ToString();
            string TimeList = HttpContext.Current.Request.Cookies["View"]["Time"].ToString();
            string[] PArr = ProductList.Split('|');
            string[] TimeArr = TimeList.Split('|');
            for (int i = 0; i < PArr.Length - 1; i++)
            {
                if (PArr[i].ToString() == ProductID)
                {
                    return "2";
                }
            }
            HttpContext.Current.Response.Cookies["View"]["ProductID"] = ProductList + ProductID + "|";
            HttpContext.Current.Response.Cookies["View"]["Time"] = TimeList + DateTime.Now.ToShortDateString() + "|";
            return "1";
        }
        else
        {
            HttpContext.Current.Response.Cookies["View"]["ProductID"] = ProductID + "|";
            HttpContext.Current.Response.Cookies["View"]["Time"] = DateTime.Now.ToShortDateString() + "|";

            return "1";
        }
    }
    #endregion

    #region 字符中"替换为'
    public static string Getstr(string str)
    {
        return str.Replace('"','\'');
    }
    #endregion

    #region 返回当前用户购物车ID 暂无用



    /// <summary>
    /// 返回当前用户的购物车ID
    /// </summary>
    /// <returns>返回当前用户的购物车ID</returns>
    public static String GetShoppingCartID()
    {
        HttpContext Context = HttpContext.Current;
        // 如果该用户已经通过验证后登录了系统, 那么以该用户的 CustomerId作为购物车ID
        if (Context.User.Identity.Name != "")
        {
            return Context.User.Identity.Name;
        }
        // 否则, 如果浏览器Cookie中已经分配给该用户一个购物车ID
        if (Context.Request.Cookies["ShoppingCartID"] != null)
        {
            return Context.Request.Cookies["ShoppingCartID"].Value;
        }
        else
        {
            // 利用System.Guid Class产生一个随机GUID(全球唯一标识号)
            Guid TempCartId = Guid.NewGuid();
            // 回写到客户端指定的cookie中



            Context.Response.Cookies["ShoppingCartID"].Value = TempCartId.ToString();
            // 同时返回 TempCartId
            return TempCartId.ToString();
        }
    }
    #endregion

    #region 订单来源初始化



    public static string OrderFrom
    {
        get
        {
            return System.Configuration.ConfigurationManager.AppSettings["OrderF"].ToString(); 
        }
    }
    #endregion

    /// <summary>
    /// 返回会员信息0会员编号,1会员折扣价 2 折上折折扣 3 折上折最大有效折扣



    /// </summary>
    
    public static string GetValue(int index)
    {
        string indintityName = HttpContext.Current.User.Identity.Name;
        string[] temp = indintityName.Split('|');
        if (temp[index] == "")
        {
            return "1";
        }
        else
        {
            return temp[index];
        }
        
    }
    #region 正则表达式



    public static string FilterScript(string content)
    {
        if (content == null || content == "")
        {
            return content;
        }
        string regexstr = @"(?i)<script([^>])*>(\w|\W)*</script([^>])*>";//@"<script.*</script>";
        content = Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        content = Regex.Replace(content, "<script([^>])*>", string.Empty, RegexOptions.IgnoreCase);
        return Regex.Replace(content, "</script>", string.Empty, RegexOptions.IgnoreCase);
    }

    public static string FilterIFrame(string content)
    {
        if (content == null || content == "")
        {
            return content;
        }
        string regexstr = @"(?i)<iframe([^>])*>(\w|\W)*</iframe([^>])*>";//@"<script.*</script>";
        content = Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        content = Regex.Replace(content, "<iframe([^>])*>", string.Empty, RegexOptions.IgnoreCase);
        return Regex.Replace(content, "</iframe>", string.Empty, RegexOptions.IgnoreCase);
    }

    public static string CheckHtml(string content)
    {
        string regexfont1 = @"(?i)<font([^>])*>(\w|\W)*</font([^>])*>";//@"<script.*</script>";
        string regexfont2 = @"<font([^>])*>";
        if (Regex.IsMatch(content, regexfont2) && (!Regex.IsMatch(content, regexfont1)))
        {
            return Regex.Replace(content, regexfont2, string.Empty, RegexOptions.IgnoreCase);
        }
        return content;
    }

    public static string RemoveHtml(string content)
    {
        string newstr = FilterScript(content);
        string regexstr = @"<[^>]*>";
        return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    public static string RemoveHtmlTag(string content, string[] tags)
    {
        string regexstr1, regexstr2;
        foreach (string tag in tags)
        {
            if (tag != "")
            {
                regexstr1 = string.Format(@"<{0}([^>])*>", tag);
                regexstr2 = string.Format(@"</{0}([^>])*>", tag);
                content = Regex.Replace(content, regexstr1, string.Empty, RegexOptions.IgnoreCase);
                content = Regex.Replace(content, regexstr2, string.Empty, RegexOptions.IgnoreCase);
            }
        }
        return content;
    }

    public static string RemoveHtmlTag(string content, string tag)
    {
        string returnStr;
        string regexstr1 = string.Format(@"<{0}([^>])*>", tag);
        string regexstr2 = string.Format(@"</{0}([^>])*>", tag);
        returnStr = Regex.Replace(content, regexstr1, string.Empty, RegexOptions.IgnoreCase);
        returnStr = Regex.Replace(returnStr, regexstr2, string.Empty, RegexOptions.IgnoreCase);
        return returnStr;
    }

    public static string ReplaceSpace(string content)
    {
        string findstr = "(?<fore>(?:(?:[^< ])*(?:<(?:!--(?:(?:[^-])*(?:(?=-->)|-))*--|(?:[^>])+)>)?)*)[ ](?<back>(?:(?:[^< ])*(?:<(?:!--(?:(?:[^-])*(?:(?=-->)|-))*--|(?:[^>])+)>)?)*)";
        //"(?<fore>(?:[^< ]*(?:<[^>]+>)?)*)[ ](?<back>(?:[^< ]*(?:<[^>]+>)?)*)";
        string replacestr = "${fore}&nbsp;${back}";
        string targetstr = System.Text.RegularExpressions.Regex.Replace(content, findstr, replacestr, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        return targetstr;
    }

    public static string[] CatchHtmlBlock(string content, string tag)
    {
        string findstr = string.Format(@"(?i)<{0}([^>])*>(\w|\W)*</{1}([^>])*>", tag, tag);
        System.Text.RegularExpressions.MatchCollection matchs = System.Text.RegularExpressions.Regex.Matches(content, findstr, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        string[] strArray = new string[matchs.Count];
        for (int i = 0; i < strArray.Length; i++)
        {
            strArray[i] = matchs[i].Value;
        }
        return strArray;
    }

    public static bool IsNumeric(string text)
    {
        return Regex.IsMatch(text, "^\\d+$");
    }

    public static bool IsPhone(string text)
    {
        return Regex.IsMatch(text, "((d{3,4})|d{3,4}-)?d{7,8}(-d{3})*");
    }
    #endregion

    #region 实体类集合序列化为字符串
    /// 实体类集合序列化为字符串
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="objToXml"></param>
    /// <returns></returns>
    public string Serializer<T>(T objToXml)
    {
        System.IO.StringWriter writer = new System.IO.StringWriter();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(objToXml.GetType());
        serializer.Serialize(writer, objToXml);
        return writer.GetStringBuilder().ToString();
    }
    #endregion

    #region 反序列化例子
    //public Collection<T> DeSerializerCollection<T>(string sXml, Type type)
    //{
    //    XmlReader reader = XmlReader.Create(new StringReader(sXml));
    //    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);

    //    object obj = serializer.Deserialize(reader);
    //    return (Collection<T>)obj;
    //}
    #endregion

    #region 前台订单状态



    public static  string GetOrderState(string delete, string locked, string check, string acheck, string send,string pay,string orderid)
    {
        string result = "备货中";

        if (delete == "1")
        {
            result = "作废";
            return result;
        }
        if (locked == "0" && check == "0")
        {
            if (pay == "1")
            {
                result = "等待处理";
                return result;
            }
            else
            {//<a href=\"PayGo.aspx?oid=" + orderid + "\" ></a>
                result = "<font color=\"red\">未支付</font>";
                return result;
            }
        }
        if (check == "1" && acheck == "0")
        {
            result = "待查账";
            return result;
        }
        if (send == "1")
        {
            result = "已发货";
            return result;
        }        
        return result;
    }
    #endregion
    #region recofull前台订单状态




    public static string GetOrderState(string delete, string locked, string check, string acheck, string send, string pay,string received, string orderid)
    {
        string result = "备货中";

        if (delete == "1")
        {
            result = "作废";
            return result;
        }
        if (locked == "0" && check == "0")
        {
            if (pay == "1")
            {
                result = "等待处理";
                return result;
            }
            else
            {//<a href=\"PayGo.aspx?oid=" + orderid + "\" ></a>
                result = "<font color=\"red\">未支付</font>";
                return result;
            }
        }
        if (check == "1" && acheck == "0")
        {
            result = "待查账";
            return result;
        }
        if (send == "1")
        {
            if (received == "0" || received == "")
            {
                result = "已发货";
                return result;
            }
            else
            {
                result = "已收货";
                return result;
            }
        }
        return result;
    }
    #endregion

    #region 网站启用售价
    public static string GetSJ()
    {
        return System.Configuration.ConfigurationManager.AppSettings["SJ"].ToString();
    }
    #endregion

    #region 新闻中心首页每个类别显示的条数



    public static string GetNewIndexTop()
    {
        return System.Configuration.ConfigurationManager.AppSettings["New_SL"].ToString();
    }
    #endregion

    #region 截取字符串



    public static string GetSubstring(string str, int start, int lenght)
    {
        int strlen = str.Length;
        if (strlen - start < lenght)
        {
            return str;
        }
        else
        {
            return str.Substring(start, lenght);
        }
    }
    #endregion
    /// <summary>
    /// 返回基础积分倍数
    /// </summary>
    /// <returns></returns>
    #region 返回基础积分倍数
    public static decimal GetBaseBS()
    {
        return new BLL.V_VIPSET().GetBaseBS(BasePage.GetValue(0));
    }
    #endregion

    #region 返回金额达到多少可以免运费

/// <summary>
/// 此方法已被BLL.Common下的相应方法替代
/// </summary>
/// <returns></returns>

    public static decimal GetFreeStandard()
    {
        return decimal.Parse(ConfigurationManager.AppSettings["WLFREE"]);
    }
    #endregion

    #region 返回仓库代码
    public static string GetCKDM()
    {
        return ConfigurationManager.AppSettings["CKDM"].ToString();
    }
    #endregion
    #region 返回库位代码
    public static string GetKWDM()
    {
        return ConfigurationManager.AppSettings["KWDM"].ToString();
    }
    #endregion

    #region 留言类型枚举
    public enum MessageType
    {
        MESSAGE = 0,//留言
        COMPLAIN = 1,//投诉
        CONSULT = 2,//询问
        AFTERSALING = 3,//售后
        FORSHOPPING = 4,//求购
        COMMON = 5 //普通（公共留言类型）


    }
    #endregion

    #region 过滤危险字符
    /// <summary>
    /// 过滤危险字符
    /// </summary>
    /// <param name="input">需要过滤的字符</param>
    /// <returns>过滤后的字符</returns>
    public static string FilterInput(string input)
    {
        return input.Replace("'", "’").Replace("\"", "“").Replace("-", "－").Replace("=", "＝").Replace("<", "＜").Replace(">", "＞").Replace(",", "，").Replace("(", "（").Replace(")", "）").Replace("%", "").Replace('"', '\"').Replace("\n", "<br/>").Replace("\\", "＼"); 
    }
    #endregion

    #region 返回指定广告内容
    public static string GetAD(string id)
    {
        string result = "";
        try
        {
            Model.WEBEDITORAD model = new Model.WEBEDITORAD();
            model = new BLL.WEBEDITORAD().GetModel(int.Parse(id));
            if (model != null)
            {
                result = model.WEBEDITORAD_CONTENT;
            }
        }
        catch
        { }
        return result;
    }
    #endregion

    #region 充值成功

    /// <summary>
    /// 充值成功，更新本地数据
    /// </summary>
    /// <param name="orderid">订单号</param>
    /// <param name="paydm">网关交易号</param>
    /// <param name="paym">支付金额</param>
    /// <param name="buyeremail">买家email</param>
    /// <param name="_time">时间</param>
    /// <param name="type">类型 支付宝，快钱</param>
    /// <returns></returns>
    public static bool AddMoney(string orderid, string paydm, string paym, string buyeremail, string _time,string type)
    {
        bool retValue = false;

        string UserCode = orderid.Substring(orderid.IndexOf("_") + 3, orderid.Length - orderid.IndexOf("_") - 3);

        string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
        Model.PAYTYPE paytype = new BLL.PAYTYPE().GetModel(type);

        StringBuilder StyleDB = new StringBuilder();
        StringBuilder ErpDB = new StringBuilder();

        DataSet ds = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(UserCode);
        string dm = new BLL.V_VIPSET().GetModelByGKDM(UserCode).DM;
        if (ds.Tables[0].Rows.Count == 0)
        {
            StyleDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, 0));
            ErpDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, 0));
        }

        //写入汇款流水帐


        StyleDB.Append("insert into REMITTANCE values(" + orderid + ",'" + UserCode + "','" + paytype.PT_NAME + "','" + paydm + "'," + paym + ",'" + _time + "','" + UserCode + "','000',1,'" + UserCode + "','" + _time + "','" + _time + "','" + buyeremail + "')");

        //充值，同时生成一张已经审核的结余款调整单，同时修改用户当前金额和可用发货金额 
        StyleDB = new StringBuilder();
        ErpDB = new StringBuilder();

        string newID = new BLL.BALANCEADJUST().GetNewID();
        BLL.Common.ADDLSH("300400102");
        int remittanceId = new BLL.REMITTANCE().getMaxId();
        remittanceId = remittanceId + 1;

        StyleDB.Append(string.Format("insert into BALANCEADJUST(BA_ID,BA_TYPE,BA_CREATER,BA_CREATEDATE,BA_CHECK,BA_CHECKER,BA_CHECKDATE,BA_RID) values('{0}','{1}','{2}','{3}',{4},'{5}','{6}','{7}')|", newID, "011", UserCode, Convert.ToDateTime(_time), 1, UserCode, Convert.ToDateTime(_time), remittanceId));// 调整单主表



        DataSet dsDQJE = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(UserCode);
        decimal balance = DBUtility.SqlHelper.GetDecimal(dsDQJE.Tables[0].Rows[0]["DQJE_1"]);
        balance = balance + Convert.ToDecimal(paym);

        StyleDB.Append(string.Format("insert into BADETAIL(BAD_ID,BAD_DETAILCODE,BAD_CUSTOMERCODE,BAD_AMT,BAD_BALANCE,BAD_NOTE,[BAD_FIELD1],[BAD_FIELD2]) values('{0}',{1},'{2}',{3},{4},'{5}','{6}','{7}')|", newID, 1, UserCode, Convert.ToDecimal(paym), balance,
            "前台" + paytype.PT_NAME + "充值", paytype.PT_CODE, paydm));

        //同步更新用户当前金额
        StyleDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));
        ErpDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));

        decimal credit = new BLL.V_VIPSET().GetModelByGKDM(UserCode).BYZD12;//信用额度
        decimal accountAmt = credit + balance;//账户当前余额加信用额度


        //同步更新可用发货金额 
        StyleDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));
        ErpDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));


        string[] cmdStyle = StyleDB.ToString().TrimEnd('|').Split('|');
        string[] cmdErp = ErpDB.ToString().TrimEnd('|').Split('|');

        WEB.ERP.Service erpService = new WEB.ERP.Service();
        retValue = erpService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, cmdStyle, cmdErp);

        return retValue;

    }
    #endregion
}
